<template>
  <div class="forgot-password-container">
    <div class="forgot-password-form">
      <h2>找回密码</h2>
      <el-form ref="resetFormRef" :model="resetForm" :rules="rules" @submit.prevent="handleResetPassword">
        <el-form-item prop="studentId">
          <el-input v-model="resetForm.studentId" placeholder="请输入学号" prefix-icon="User" />
        </el-form-item>

        <el-form-item prop="phone">
          <el-input v-model="resetForm.phone" placeholder="请输入手机号" prefix-icon="Phone" />
        </el-form-item>

        <el-form-item prop="smsCode">
          <div class="captcha-input-container">
            <el-input v-model="resetForm.smsCode" placeholder="请输入短信验证码" prefix-icon="Lock" />
            <el-button type="primary" :disabled="countdown > 0 || loading" @click="sendSmsCode">
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item prop="newPassword">
          <el-input v-model="resetForm.newPassword" placeholder="请输入新密码" type="password" show-password
            prefix-icon="Lock" />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input v-model="resetForm.confirmPassword" placeholder="请再次输入新密码" type="password" show-password
            prefix-icon="Lock" />
        </el-form-item>

        <el-button type="primary" class="reset-btn" :loading="loading" @click="handleResetPassword" style="width: 100%">
          {{ loading ? '重置中...' : '重置密码' }}
        </el-button>

        <div class="login-link">
          记得密码？<router-link to="/login">返回登录</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormRules, FormInstance } from 'element-plus'

// 使用Element Plus表单引用
const resetFormRef = ref<FormInstance>()

interface ResetForm {
  studentId: string
  phone: string
  smsCode: string
  newPassword: string
  confirmPassword: string
}

// 路由
const router = useRouter()

// 表单数据
const resetForm = reactive<ResetForm>({
  studentId: '',
  phone: '',
  smsCode: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = reactive<FormRules<ResetForm>>({
  studentId: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 加载状态
const loading = ref(false)
const countdown = ref(0)
const smsCodeValue = ref('') // 存储生成的短信验证码，实际项目中应由后端生成

// 发送短信验证码
const sendSmsCode = async () => {
  if (!resetFormRef.value) return

  try {
    await resetFormRef.value.validateField('phone')
    await resetFormRef.value.validateField('studentId')

    // 模拟发送短信验证码请求
    // 实际项目中应该调用后端接口
    console.log('发送短信到手机号:', resetForm.phone)
    console.log('学号:', resetForm.studentId)

    // 模拟生成验证码（实际应由后端生成）
    smsCodeValue.value = Math.floor(100000 + Math.random() * 900000).toString()
    console.log('生成的短信验证码:', smsCodeValue.value) // 仅用于测试，实际不应该在控制台显示

    // 显示提示
    ElMessage.success(`短信验证码已发送，验证码为：${smsCodeValue.value}（仅用于测试环境）`)

    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    console.error('发送短信失败:', error)
  }
}

// 处理重置密码
const handleResetPassword = async () => {
  if (!resetFormRef.value) return

  try {
    await resetFormRef.value.validate()

    // 验证短信验证码
    // 模拟环境下的验证码验证
    // 实际项目中应该由后端验证
    if (resetForm.smsCode !== smsCodeValue.value) {
      ElMessage.error('短信验证码错误')
      return
    }

    loading.value = true

    // 模拟重置密码请求
    // 实际项目中应该调用后端接口
    console.log('重置密码信息:', {
      studentId: resetForm.studentId,
      phone: resetForm.phone,
      newPassword: resetForm.newPassword
    })

    // 模拟成功响应
    ElMessage.success('密码重置成功，请使用新密码登录')
    router.push('/login')
  } catch (error) {
    console.error('密码重置失败:', error)
    ElMessage.error('密码重置失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.forgot-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.forgot-password-form {
  background: white;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 400px;
}

.forgot-password-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.captcha-input-container {
  display: flex;
  gap: 10px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #666;
}

.login-link a {
  color: #409eff;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}
</style>